package com.xiangxiao.rpan.authority.oauth;

import com.xiangxiao.rpan.authority.model.UserInfo;
import com.xiangxiao.rpan.authority.model.UserRoleInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/4/13 16:28
 */
public class UserOAuthDetail implements UserDetails {
  /**
   * 登录的账号:可以是账号、手机号码、邮箱
   */
  private String loginAccount;

  /**
   * 用户信息
   */
  private UserInfo userInfo;

  public UserOAuthDetail(String loginAccount, UserInfo userInfo) {
    this.loginAccount = loginAccount;
    this.userInfo = userInfo;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    Collection<UserRoleInfo> authorities = new HashSet<>();
    List<UserRoleInfo> list = getUserRoleInfo();
    if (CollectionUtils.isNotEmpty(list)) {
      for (UserRoleInfo userRoleInfo : list) {
        authorities.add(userRoleInfo);
      }
    }
    return authorities;
  }

  @Override
  public String getPassword() {
    return userInfo.getUserVo().getPassword();
  }

  @Override
  public String getUsername() {
    return loginAccount;
  }


  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  /**
   * 获取用户的id
   *
   * @return
   */
  public Long getUserId() {
    return userInfo.getUserVo().getId();
  }

  public UserInfo getUserInfo() {
    return userInfo;
  }

  private List<UserRoleInfo> getUserRoleInfo() {
    return userInfo.getUserRoleInfos();
  }
}
